import axios from 'axios'
import router from '@/router/routers'
import { Notification, Loading } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import Config from '@/settings'
import Cookies from 'js-cookie'

// 请求队列
// let requestQueue = []
let isRefreshing = false
let loadingInstance = null

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/',
  timeout: Config.timeout,
  // 请求重试配置
  retry: 0,
  retryDelay: 1000
})

// request拦截器
service.interceptors.request.use(
  config => {
    // 添加请求标识，避免重复请求
    const requestKey = `${config.method}_${config.url}_${JSON.stringify(config.params)}_${JSON.stringify(config.data)}`
    config.requestKey = requestKey

    // Token处理
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    // 如果是FormData，不设置Content-Type，让浏览器自动设置boundary
    if (!(config.data instanceof FormData)) {
      config.headers['Content-Type'] = 'application/json'
    }

    // 显示loading（POST/PUT/DELETE请求）
    if (['post', 'put', 'delete'].includes(config.method) && !config.hideLoading) {
      loadingInstance = Loading.service({
        text: '处理中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }

    return config
  },
  error => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // 关闭loading
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }

    // 根据业务需求处理响应数据
    const { code, data, message } = response.data

    // 如果响应中有code字段，按照原逻辑处理
    if (code !== undefined) {
      if (code === 200 || code === 0) {
        return data || response.data
      } else {
        Notification.error({
          title: message || '请求失败',
          duration: 5000
        })
        return Promise.reject(new Error(message || '请求失败'))
      }
    } else {
      // 如果没有code字段，直接返回响应数据（适用于验证码等接口）
      return response.data
    }
  },
  error => {
    // 关闭loading
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }

    // 请求重试逻辑
    const config = error.config
    if (config && config.retry > 0) {
      config.retry--
      return new Promise(resolve => {
        setTimeout(() => resolve(service(config)), config.retryDelay || 1000)
      })
    }

    // Blob错误处理
    if (error.response?.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function() {
        const errorMsg = JSON.parse(reader.result).message
        Notification.error({
          title: errorMsg,
          duration: 5000
        })
      }
      return Promise.reject(error)
    }

    let code = 0
    try {
      code = error.response?.data?.status || error.response?.status
    } catch (e) {
      if (error.toString().indexOf('timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 5000
        })
        return Promise.reject(error)
      }
    }

    if (code) {
      if (code === 401) {
        // Token过期处理
        if (!isRefreshing) {
          isRefreshing = true
          store.dispatch('LogOut').then(() => {
            Cookies.set('point', 401)
            location.reload()
          }).finally(() => {
            isRefreshing = false
          })
        }
      } else if (code === 403) {
        router.push({ path: '/401' })
      } else {
        const errorMsg = error.response?.data?.message || '请求失败'
        Notification.error({
          title: errorMsg,
          duration: 5000
        })
      }
    } else {
      Notification.error({
        title: '网络连接异常',
        duration: 5000
      })
    }

    return Promise.reject(error)
  }
)
export default service
